package code.springboot.mybatis.interceptor;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Intercepts(
        @Signature(type = StatementHandler.class, method = "prepare",args = {Connection.class,Integer.class})
)
@Component
public class MonitorInterceptor  implements Interceptor{

    private Logger logger = LoggerFactory.getLogger(getClass());

    Map<String, AtomicInteger> monitorSqlMap = new ConcurrentHashMap<>();

    AtomicInteger sqlCount = new AtomicInteger();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        logger.info("<-------------MonitorInterceptor---------------->");
        long startTime = System.currentTimeMillis();
        StatementHandler statement = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statement.getBoundSql();
        String sql = boundSql.getSql();
        long endTime = System.currentTimeMillis();
        logger.info("执行 SQL 执行耗时:{}",endTime - startTime);
        logger.info("拦截sql: " + sql);
        sqlCount.getAndIncrement();
        logger.info("执行SQL {} 次",sqlCount);
        return invocation.proceed();
    }
}
